package com.stu.config.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 1、配置Reaml——自定义Realm
 * 2、配置SecurityManager
 * 3、配置ShiroFilterFactoryBean
 */
@Configuration
public class ShiroConfig {
    @Bean
    public MyRealm myRealm(){
        return new MyRealm();
    }
    @Bean
    public SecurityManager securityManager(Realm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(realm);
        return securityManager;
    }
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        //定义过滤链——key是资源、value是权限
        Map<String, String> filterChainMap = new LinkedHashMap<>();
        /*
        anon：无需认证即可访问
        authc：必须认证才能访问
        user：必须拥有记住我功能才能访问
        role：必须拥有角色才能访问
        perms：必须拥有权限才能访问
        过滤链未设置的资源不会被拦截
         */
//        filterChainMap.put("/user/toAdd","anon");
//        filterChainMap.put("/user/toDelete","authc");
        filterChainMap.put("/user/toAdd","perms[user:add]");
//        filterChainMap.put("/user/toDelete","perms[user:delete]");
//        filterChainMap.put("/user/*","anon");

        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();

        factoryBean.setSecurityManager(securityManager);//设置安全管理器
        factoryBean.setFilterChainDefinitionMap(filterChainMap);//设置过滤链
        factoryBean.setLoginUrl("/toLogin");//设置登录页面（如果被authc拦截（未认证）则会跳转到该页面），若不设置该选项则页面报异常
        factoryBean.setUnauthorizedUrl("/unAuthr");//设置未授权页面（如果被perms拦截（未授权）则会跳转到该页面），若不设置该选项则页面报异常
        return factoryBean;
    }


    //shiro整合thymeleaf
    @Bean
    public ShiroDialect shiroDialect(){ return new ShiroDialect(); }
}
